package com.shelpe.services.sinbad.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.shelpe.services.sinbad.entity.jpa.MessageAttention;
import com.shelpe.services.sinbad.entity.jpa.User;
import com.shelpe.services.sinbad.repository.jpa.MessageAttentionRepository;
import com.shelpe.services.sinbad.repository.jpa.UserRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.Setter;

@RestController
@RequestMapping(value = "/sinbadservice")
@Api("消息相关的API")
@Setter
public class MessageController {
	@Autowired
	private MessageAttentionRepository messageAttentionRepository;
	@Autowired
	private UserRepository userRepository;

	@ApiOperation("消息关注度记录api")
	@RequestMapping(path = "/users/{user_id}/messageAttentions", method = RequestMethod.POST)
	public MessageAttentionDto create(@PathVariable("user_id") long userID, @RequestBody MessageAttentionDto dto) {
		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "user_not_exist");
		MessageAttention.MessageAttentionPK pk = new MessageAttention.MessageAttentionPK();
		pk.setMessageID(dto.getMessageID());
		pk.setUserID(userID);
		MessageAttention messageAttention = this.messageAttentionRepository.findOne(pk);
		if (messageAttention == null) {
			messageAttention = new MessageAttention();
			messageAttention.setMessageID(dto.getMessageID());
			messageAttention.setUserID(userID);
			messageAttention.setNick(user.getNick());
			this.messageAttentionRepository.save(messageAttention);
		}

		return dto;
	}

	@Data
	public static class MessageAttentionDto {
		@JsonProperty("message_id")
		private long messageID;
	}
}
